<?php

namespace App\Logging\Service;

use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Log;
use Ramsey\Uuid\Uuid;

class LogService
{
    /**
     * @var static 单例模式
     */
    protected static $instance;

    /**
     * 单例模式
     */
    public static function getInstance()
    {
        if (static::$instance instanceof static) {
            return static::$instance;
        }
        static::$instance = new static();
        return static::$instance;
    }

    protected $traceId;
    protected $subTraceId;
    protected $module = '';

    public function getModule()
    {
        if ($this->module) {
            return $this->module;
        }
        if (App::runningInConsole()) {
            $this->module = 'cmd';
        }
        else {
            $path = request()->path();
            $array = explode('/', $path);
            $this->module = 'api-' . strtolower($array[0]);
        }
        return $this->module;
    }

    public function getTraceId()
    {
        if (!$this->traceId) {
            $this->setTraceId();
        }
        return $this->traceId;
    }

    public function setTraceId($traceId = '')
    {
        $this->traceId = $traceId ?: str_replace('-', '', Uuid::uuid4()->toString());
    }

    public function getSubTraceId()
    {
        return $this->subTraceId;
    }

    public function setSubTraceId($subTraceId = '')
    {
        $this->subTraceId = $subTraceId ?: uniqid();
    }

    public function getDefaultDriver()
    {
        /* @var $logManager \Illuminate\Log\LogManager */
        $logManager = Log::getFacadeRoot();
        return $logManager->getDefaultDriver();
    }

    public function getFinalTraceId()
    {
        $traceId = $this->getTraceId();
        if ($this->getSubTraceId()) {
            $traceId .= '|' . $this->getSubTraceId();
        }
        if ($this->getModule()) {
            $traceId .= '.' . $this->getModule();
        }
        return $traceId . '.' . $this->getDefaultDriver();
    }
}
